package com.zsyh.changshang.basic;









import com.zsyh.changshang.BuildConfig;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.zsyh.changshang.basic.MyAppliaction.getIMEI;


/**
 * 接口文档地址 http://agent.miaoyouche.cn:81/doc.html
 * H5地址:http://pack.miaoyouche.cn:81/partner/index.html#/
 *
 * @author shichen 754314442@qq.com
 *         Created by Administrator on 2018/11/19.
 */
public class RetrofitHelper {
    private final String TAG = "RetrofitHelper";
    private static RetrofitHelper INSTANCE;
    private final int REQUEST_TIME_OUT = 5;
   // public String debugUrl = "https://www.zzzsyh.com/";
   public String debugUrl = "http://192.168.2.13:8096/";
    public String releaseUrl = "http://192.168.2.13:8096/";
    private Retrofit mRetrofit;
    private OkHttpClient mOkHttpClient;
    private RetrofitHelper() {
        mOkHttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .addInterceptor(new RequestInterceptor())
                .connectTimeout(REQUEST_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(REQUEST_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(REQUEST_TIME_OUT, TimeUnit.SECONDS).build();
        mRetrofit = new Retrofit.Builder()
                .client(mOkHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(BuildConfig.DEBUG ? debugUrl : releaseUrl)
                .build();
    }

    public static RetrofitHelper getInstance() {
        if (INSTANCE == null) {
            synchronized (RetrofitHelper.class) {
                if (INSTANCE == null) {
                    INSTANCE = new RetrofitHelper();
                }
            }
        }
        return INSTANCE;
    }


    /**
     * 使用原来的baseUrl
     * @return
     */
    public Retrofit getRetrofit() {
        return mRetrofit;
    }
    public static class RequestInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request;
            RequestBody body = chain.request().body();
           /* MediaType type = body.contentType();
            Log.e("MediaTypes", type.type().toString());*/


            request = chain.request()
                    .newBuilder()
                    .addHeader("agent", "Android")
                    .addHeader("code", getIMEI(MyAppliaction.getContext()))
                    .build();

            return chain.proceed(request);
        }
    }



}
